import copy
import os

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from SecureHelperServer.settings import formatResponseData, MEDIA_ROOT, MEDIA_URL
from utils.conf import Response, newID
from utils.custom import MyJWTAuthentication


class UploadImageView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        note上传图片
        """
        data = copy.deepcopy(formatResponseData)
        try:
            imageFile = request.FILES.get("imageFile")

            if not imageFile:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            image = imageFile.read()
            imageType = imageFile.name.split(".")[-1]
            imageName = f"{request.user.uid}_{newID()}.{imageType}"
            uploadPath = os.path.join(MEDIA_ROOT, "userNotesMedia", "userNotesImages", imageName)
            with open(uploadPath, 'wb') as f:
                f.write(image)

            url = os.path.join(f'{MEDIA_URL}', "userNotesMedia", "userNotesImages", imageName)
            data["data"]["url"] = url

            return Response(data=data, loggerMsg=f"note上传图片：成功，imageName={imageName}")

        except Exception as e:
            return Response(data=data, responseMsg="图片上传失败",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
